//
//  AKRemoteNotificationHelper.m
//  96166打车
//
//  Created by guoshikeji_a on 2016/12/14.
//  Copyright © 2016年 SX. All rights reserved.
//

#import "AKRemoteNotificationHelper.h"

#import "NSDate+Utilities.h"

static NSString *const kAKCDTOKENKEY = @"kAKCDTOKENKEY";

@implementation AKRemoteNotificationHelper

+ (NSString *)deviceToken {
    return [[NSUserDefaults standardUserDefaults] objectForKey:kAKCDTOKENKEY];
}

+ (void)saveDeviceToken:(NSString *)token {
    if (token) {
        
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:kAKCDTOKENKEY];
    }else {

        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kAKCDTOKENKEY];
    }
}

+ (void)requestPushNotificationAuthorization:(UIApplication *)application delegate:(id)delegate {
    //iOS 10 later
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        //必须写代理，不然无法监听通知的接收与点击事件
        center.delegate = delegate;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error && granted) {
                //用户点击允许
                NSLog(@"注册成功");
            }else{
                //用户点击不允许
                NSLog(@"注册失败");
            }
        }];
        
        // 可以通过 getNotificationSettingsWithCompletionHandler 获取权限设置
        //之前注册推送服务，用户点击了同意还是不同意，以及用户之后又做了怎样的更改我们都无从得知，现在 apple 开放了这个 API，我们可以直接获取到用户的设定信息了。注意UNNotificationSettings是只读对象哦，不能直接修改！
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            NSLog(@"========%@",settings);
        }];
    } else if (@available(iOS 8.0, *)){
        //iOS 8 - iOS 10系统
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    else {
        //iOS 8.0系统以下
        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
    }
    
    
    //注册远端消息通知获取device token
    [application registerForRemoteNotifications];
}

+(instancetype)shared {
    
    static AKRemoteNotificationHelper *sm = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        sm = [[[self class] alloc]init];
    });
    return sm;
}

- (void)notificationWithMessage:(NSString *)message userInfo:(NSDictionary *)userInfo delay:(NSUInteger)delay {
   
    //设置延时，单位：秒
    
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:delay];
    
    [self notificationWithMessage:message userInfo:userInfo soundName:nil fireDate:date];
}

- (void)notificationWithMessage:(NSString *)message
                       userInfo:(NSDictionary *)userInfo
                      soundName:(NSString *)soundName
                       fireDate:(NSDate *)fireDate {
    [self notificationWithTitle:nil message:message userInfo:userInfo soundName:soundName fireDate:fireDate];
}

- (void)notificationWithTitle:(NSString *)title
                      message:(NSString *)message
                     userInfo:(NSDictionary *)userInfo
                    soundName:(NSString *)soundName
                     fireDate:(NSDate *)fireDate {

    
    // ios 10之前
    CGFloat version = [[UIDevice currentDevice].systemVersion doubleValue];
    // 注册本地推送
    if (version >= 8.0 && version< 10.0) {
        
        // 10.0之前推送设置...
        //创建一个本地推送
        
        UILocalNotification *noti = [[UILocalNotification alloc] init];
        
        if (noti) {
            
            //设置推送时间
            
            noti.fireDate = fireDate;
            
            //设置时区
            
            noti.timeZone = [NSTimeZone defaultTimeZone];
            
            //设置重复间隔
            
            noti.repeatInterval = 0;
            //        noti.repeatInterval = kCFCalendarUnitDay;
            
            //推送声音
            if (soundName) {
                noti.soundName = soundName;
            }else {
                noti.soundName = UILocalNotificationDefaultSoundName;
            }
            
            //内容
            noti.alertBody = message;
            
            noti.alertTitle = title;
            
            //显示在icon上的红色圈中的数子
            
            noti.applicationIconBadgeNumber = 1;
            
            //设置userinfo方便在之后需要撤销的时候使用
            noti.userInfo = userInfo;
            
            //添加推送到uiapplication
            UIApplication *app = [UIApplication sharedApplication];
            [app scheduleLocalNotification:noti];
        }
        
    }else if(version >= 10.0){
        // 使用 UNUserNotificationCenter 来管理通知
        UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
        
        //需创建一个包含待通知内容的 UNMutableNotificationContent 对象，注意不是 UNNotificationContent ,此对象为不可变对象。
        UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
        content.title = title;
        content.body = message;
        // 使用定制声音
        if (soundName) {
            
            content.sound = [UNNotificationSound soundNamed:soundName];
        }else {
            // 默认声音
             content.sound =[UNNotificationSound defaultSound];
            
        }
        
        
        // 在 alertTime 后推送本地推送
        NSTimeInterval noticTimeInterval = [fireDate timeIntervalSinceDate:[NSDate date]];
        if (noticTimeInterval < 0) {
            return;
        }
        UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:noticTimeInterval repeats:NO];
        
//        NSDateComponents *dateComponents = [NSDateComponents ]
//        UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:nil repeats:NO];
        UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:userInfo[@"schedule_key"]
                                                                              content:content trigger:trigger];
        
        //添加推送成功后的处理！
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {

        }];
    }
}

- (void)cancelLocalNotificationByUserInfoKey:(NSString *)key value:(id)value {
    NSArray *localNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
    
    if (localNotifications.count > 0) {
        
        [localNotifications enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if ([obj isKindOfClass:[UILocalNotification class]]) {
                UILocalNotification *noti = obj;
                if ([noti.userInfo objectForKey:key] &&
                    [[noti.userInfo objectForKey:key] isEqual:value]) {
                    
                    [[UIApplication sharedApplication] cancelLocalNotification:noti];
                }
            }
        }];
    }
}

- (void)cancelAllLocalNotifications {
 
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}
@end
